"use server";
import { db } from "@/lib/db";
import { RegisterSchema } from "@/schemas";
import * as z from "zod";
import { hash } from "bcryptjs";
import { getUserByEmail } from "@/data/user";
export const register = async (values: z.infer<typeof RegisterSchema>) => {
  const validateFilelds = RegisterSchema.safeParse(values);
  if (!validateFilelds.success) {
    return { code: 1, data: "Invalid fields" };
  }
  const { password, email, name } = validateFilelds.data;
  const hashedPassword = await hash(password, 10);

  const existingUser = await getUserByEmail(email);
  if (existingUser) {
    return {
      code: 1,
      data: "Email already in user!",
      message: "Email already in user!",
    };
  }

  await db.user.create({
    data: {
      name,
      email,
      password: hashedPassword,
    },
  });
  return { code: 0, data: "User created!" };
};
